<template>
  <div>
    <div class="wrap">
      <div class="wrap_header">
        <!--  -->
        <div class="wrap_headerTitle">
          <div class="wrap_headerTitleRow">
            <span @click="goPlay" class="iconfont icon-arrowdown"></span>
          </div>
        </div>
        <!--  -->
      </div>
      <div class="wrap_content">
        <div
          class="wrap_content_box animate__animated animate__bounceInUp"
          v-for="(item, index) in talkData"
          :key="index"
        >
          <div class="commentCon" v-if="item.talkCon.indexOf('mp3') === -1">
            <img :src="item.userImg" class="commentCon_rowHeader" />
            <span class="commentCon_rowTitle">{{ item.userName }} </span>
            <span class="commentCon_rowText">{{ item.talkCon }}</span>
          </div>
          <div class="commentCon" v-if="item.talkCon.indexOf('mp3') !== -1">
            <img :src="item.userImg" class="commentCon_rowHeader" />
            <span class="commentCon_rowTitle">{{ item.userName }} </span>
            <span class="commentCon_rowText"
              ><i class="iconfont icon-bofang" @click="play(item.talkId)"></i
            ></span>
          </div>
        </div>
      </div>

      <div class="wrap_footer">
        <div class="wrap_footerRow">
          <span
            @click="flag"
            v-show="inputFlag === false"
            class="iconfont icon-jianpan"
          ></span>
          <span
            @click="flag"
            v-show="inputFlag"
            class="iconfont icon-maikefeng"
          ></span>
        </div>
        <div class="wrap_footerRow">
          <div
            @touchstart="mouseStart"
            @touchend="mouseEnd"
            v-show="inputFlag === false"
            class="wrap_footerRowInput1"
            type="text"
          >按住说话</div>
          <input
            v-show="inputFlag"
            v-model="value"
            @input='word'
            class="wrap_footerRowInput"
            type="text"
          />
          <button v-show="inputFlag" @click="send">发送</button>
          <audio ref="audio" :src="talkCon"></audio>
          <div id='alert' v-show="recordFlag">
            <p>松开停止录音</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as api from "../../../api/home";
import recording from "../../../js/recorder";
import sensitiveWord from '../../../js/sensitiveWord'
export default {
  data() {
    return {
      talkData: [],
      introduceId: "",
      item: {},
      inputFlag: false,
      value: "",
      userId: "",
      talkId: "",
      // 上传录音
      form: {
        audioUrl: "/api/project/voiceUploading",
      },
      recorder: null,
      mp3Name: "",
      recordFlag:false,
      // 播放
      src: "",
    };
  },
  mounted() {
    this.introduceId = this.$route.params.id;
    api
      .toPingLun({ introduceId: this.introduceId })
      .then((res) => {
        res.data.sort((a, b) => {
          return a.talkId - b.talkId;
        });
        this.talkData = res.data;
        this.item = res.data[0];
        console.log(22222,this.talkData);
        console.log(33333,this.item);
      })
      .catch((err) => {
        console.log("失败", err);
      });
  },
  computed: {
    talkCon() {
      try {
        return this.src;
      } catch (err) {
        return null;
      }
    },
  },
  methods: {
    goPlay() {
      this.$router.push({
        path: "/tgs",
        query: { episode: JSON.stringify(this.item) },
      });
    },
    flag() {
      this.inputFlag = !this.inputFlag;
    },


    send() {
      api
        .findUser({ userName: this.$store.state.order.user.name })
        .then((res) => {
          this.userId = res.data.userId;
        })
        .catch((err) => {
          console.log("失败", err);
        });
      api
        .booktalk()
        .then((res) => {
          this.talkId = Number(res.data[res.data.length - 1].talkId) + 1;
        })
        .catch((err) => {
          console.log("失败", err);
        });
      setTimeout(() => {
        let booktalkObj = {
          bookId: this.item.bookId,
          talkId: this.talkId,
          introduceId: this.item.introduceId,
          userId: this.userId,
          talkCon: this.value,
        };
        api
          .addBooktalk(booktalkObj)
          .then((res) => {
            // console.log(222222, res.data);
          })
          .catch((err) => {
            console.log("失败", err);
          });
        api
          .toPingLun({ introduceId: this.introduceId })
          .then((res) => {
            res.data.sort((a, b) => {
              return a.talkId - b.talkId;
            });
            this.talkData = res.data;
            this.item = res.data[0];
          })
          .catch((err) => {
            console.log("失败", err);
          });
        this.value = "";
      }, 500);
    },

    
    // 长按说话
    mouseStart() {
      recording.get((rec) => {
        // 当首次按下时，要获取浏览器的麦克风权限，所以这时要做一个判断处理
        if (rec) {
          // 首次按下，只调用一次
          if (this.flag) {
            this.mouseEnd();
            this.flag = false;
          } else {
            this.recorder = rec;
            this.recorder.start();
            this.recordFlag = true;
          }
        }
      });
    },
    // 松开时上传语音
    mouseEnd() {
      if (this.recorder) {
        this.recorder.stop();
        this.recordFlag = false;
        // 获取语音二进制文件
        let bold = this.recorder.getBlob();
        // 将获取的二进制对象转为二进制文件流
        let files = new File([bold], "test.mp3", {
          type: "audio/mp3",
          lastModified: Date.now(),
        });
        // 直接可以异步上传一个二进制文件，而这个二进制文件，就是我们上面讲的Blob对象。
        let fileData = new FormData();
        fileData.append("file", files);
        // 上传服务器的接口
        api
          .voiceUploading(fileData)
          .then((res) => {
            this.mp3Name = res.data.mp3Name;
          })
          .catch((err) => {
            console.log("失败", err);
          });
        setTimeout(() => {
          // 添加数据库
          api
            .findUser({ userName: this.$store.state.order.user.name })
            .then((res) => {
              this.userId = res.data.userId;
            })
            .catch((err) => {
              console.log("失败", err);
            });
          api
            .booktalk()
            .then((res) => {
              this.talkId = Number(res.data[res.data.length - 1].talkId) + 1;
            })
            .catch((err) => {
              console.log("失败", err);
            });
          setTimeout(() => {
            let booktalkObj = {
              bookId: this.item.bookId,
              talkId: this.talkId,
              introduceId: this.item.introduceId,
              userId: this.userId,
              talkCon: `http://192.168.1.128:8888/mp3/${this.mp3Name}`,
              // talkCon: `http://localhost:5222/mp3/${this.mp3Name}`,
            };
            // 添加
            api
              .addBooktalk(booktalkObj)
              .then((res) => {})
              .catch((err) => {
                console.log("失败", err);
              });
            // 排序
            api
              .toPingLun({ introduceId: this.introduceId })
              .then((res) => {
                res.data.sort((a, b) => {
                  return a.talkId - b.talkId;
                });
                this.talkData = res.data;
                this.item = res.data[0];
              })
              .catch((err) => {
                console.log("失败", err);
              });
          }, 400);
        }, 100);

        // // 读取buff值
        // let fileData = "";
        // var fileReader = new FileReader();
        // // fileReader.readAsBinaryString(bold)
        // // fileReader.readAsText(bold)
        // console.log(bold)
        // fileReader.readAsDataURL(bold);
        // fileReader.onload = function () {
        //   fileData = fileReader.result;
        // };
        // setTimeout(() => {
        //   console.log(fileData);
        //   // axios请求文件类型的数据处理（可下载）
        //   // var url = window.URL.createObjectURL(fileData);
        //   // console.log(url);
        //   // var aLink = document.createElement("a");
        //   // aLink.style.display = "none";
        //   // aLink.download = decodeURI('fileName.mp3');
        //   // aLink.href = fileData;
        //   // document.body.appendChild(aLink);
        //   // aLink.click();
        //   // document.body.removeChild(aLink); //下载完成移除元素
        //   // window.URL.revokeObjectURL(url); //释放掉blob对象
        //   // 上传的接口
        //   let fileData = new FormData()
        //   fileData.append('file',bold)
        //   api
        //   .voiceUploading(fileData)
        //   .then((res) => {
        //     console.log(888888, res.data);
        //   })
        //   .catch((err) => {
        //     console.log("失败", err);
        //   });
        // }, 50);
      }
    },
    play(talkId) {
      api
        .booktalk()
        .then((res) => {
          res.data.forEach((item, index) => {
            if (item.talkId == talkId && item.talkCon.indexOf("mp3") !== -1) {
              this.src = item.talkCon;
              this.$nextTick(() => {
                if (this.$refs.audio.pause) {
                  this.$refs.audio.play();
                  console.log("播放成功");
                }
              });
            }
          });
        })
        .catch((err) => {
          console.log("失败", err);
        });
    },
    word() {
      sensitiveWord.forEach((item, index) => {
        if (this.value.indexOf(item) !== -1) {
            this.value=this.value.replace(`${item}`,"*")
        }
      });
    },
  },
};
</script>
<style scoped>
@import url("../../../../assets/font/iconfont.css");
.wrap {
  width: 100vw;
  height: 100vh;
  background-color: #00b396;
  position: relative;
  z-index: 10000;
  overflow: hidden;
}
.wrap_header {
  width: 100vw;
  height: 71px;
  box-shadow: 0px 1px #2dcbb4;
}
/*  copy——Maco*/
.wrap_headerTitle {
  width: 100%;
  height: 71px;
  display: flex;
  line-height: 71px;
}
.wrap_headerTitleRow:nth-child(1) {
  flex: 0.1;
}
.wrap_headerTitleRow:nth-child(1) span {
  font-size: 25px;
  color: #e1e1e1;
  margin-left: 10px;
  display: inline-block;
  margin-top: 18px;
}
.wrap_headerTitleRow:nth-child(2) {
  flex: 0.9;
}
.wrap_headerTitleRow:nth-child(2) span {
  font-size: 27px;
  color: white;
  position: absolute;
  right: 22px;
  top: 17px;
}
.wrap_contentRow_gridBtn {
  display: inline-block;
  border: none;
  border-radius: 35px;
  width: 85%;
  height: 30px;
  background: #cecece;
  color: white;
  font-weight: bold;
  line-height: 30px;
  text-align: center;
  overflow: auto;
}
/*  copy——Maco*/

.wrap_content {
  width: 100vw;
  height: calc(736px - 123px);
  overflow: auto;
}
.wrap_content_box {
  width: 100vh;
  height: 60px;
  overflow: hidden;
  padding: 10px;
}
.commentCon {
  height: 30px;
  margin: 20px 0px;
  background-color: white;
  border-radius: 35px;
  font-size: 11px;
  float: left;
}
.commentCon span {
  display: inline-block;
}

/* 7 15 11 */
.commentCon_rowHeader {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-left: 5px;
  margin-right: 5px;
  position: relative;
  left: 5px;
  top: 5px;
}
.commentCon_rowHeader img {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}
.commentCon_rowTitle {
  margin: 0 15px 0 5px;
  color: #979797;
}
.commentCon_rowText {
  padding-right: 10px;
}
.wrap_footer {
  width: 100vw;
  height: 50px;
  border-radius: 35px 35px 0 0;
  background-color: white;
  display: flex;
  position: absolute;
  bottom: 0;
}
.wrap_footerRow:nth-child(1) {
  flex: 0.2;
  text-align: center;
  line-height: 50px;
}
.wrap_footerRow:nth-child(1) span {
  flex: 0.2;
  text-align: center;
  line-height: 50px;
  font-size: 27px;
}

.wrap_footerRow:nth-child(2) {
  flex: 0.8;
  line-height: 50px;
}

/* input样式 */
.wrap_footerRowInput {
  display: inline-block;
  width: 263px;
  height: 30px;
  background-color: #f4f4f4;
  text-align: left;
  line-height: 30px;
  font-size: 15px;
  border: none;
  outline: none;
}
.wrap_footerRowInput1 {
  display: inline-block;
  width: 263px;
  height: 30px;
  background-color: #f4f4f4;
  text-align: center;
  line-height: 30px;
  font-size: 15px;
  border: none;
  outline: none;
}
/* 改变input字体 */
.wrap_footerRowInput::-webkit-input-placeholder {
  font-size: 15px;
  color: #0c1212;
  font-weight: bold;
}
.wrap_footerRow button {
  border: none;
  background: #00b396;
  padding: 5px;
  border-radius: 5px;
  color: white;
  margin-left: 8px;
}
#alert{
  position: fixed;
  top:40%;
  left:50%;
  width:200px;
  height: 100px;
  background: rgba(0,0,0,0.3);
  transform: translateX(-50%);
}
#alert p{
  color: white;
  font-size: 25px;
  text-align: center;
  line-height: 100px;
}
</style>